using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;

namespace Astro.Core
{
	/// <summary>
	/// Defines a single custom form. This object is stored in the ObjectStore
	/// </summary>
	[Serializable]
	public class CustomFormSettings
	{
		public string Name;
		public bool IsNew = true;

		public List<CustomField> Fields;

		public void Add(CustomField field)
		{
			if (field.Id == Guid.Empty)
				field.Id = Guid.NewGuid();

			if (Fields == null)
				Fields = new List<CustomField>();

			Fields.Add(field);
		}

		public bool HasFields
		{
			get { return Fields != null && Fields.Count > 0; }
		}

		public string GetHtmlForm(NameValueCollection customFieldValues, bool isNew)
		{
			NameValueCollection fieldValues = new NameValueCollection();
			foreach (CustomField cf in this.Fields)
			{
				if (customFieldValues[cf.Name] != null)
					fieldValues[cf.Id.ToString()] = customFieldValues[cf.Name];
				else
					fieldValues[cf.Id.ToString()] = customFieldValues[cf.Id.ToString()];
			}

			StringBuilder sb = new StringBuilder();
			foreach (CustomField cf in this.Fields)
			{
				switch (cf.FieldType)
				{
					case FieldType.TextBox:
						new TextFormElement(cf.Id.ToString(), cf.Name, cf.Description).Write(sb, fieldValues);
						break;
		
					case FieldType.TextArea:
						new TextAreaFormElement(cf.Id.ToString(), cf.Name, cf.Description, cf.Rows).Write(sb, fieldValues);
						break;

					case FieldType.CheckBox:
						new CheckFormElement(cf.Id.ToString(), cf.Name, cf.Description, cf.Checked, isNew).Write(sb, fieldValues);
						break;

					case FieldType.File:
						new FileFormElement(cf.Id.ToString(), cf.Name, cf.Description).Write(sb, fieldValues);
						break;

					case FieldType.WYSIWYG:
						new WYWIWYGFormElement(cf.Id.ToString(), cf.Name, cf.Description).Write(sb, fieldValues);
						break;

					case FieldType.DateTime:
						new DateTimeFormElement(cf.Id.ToString(), cf.Name, cf.Description).Write(sb, fieldValues);
						break;

					case FieldType.List:
						if (cf.ListOptions != null && cf.ListOptions.Count > 0)
						{
							ListFormElement lfe = new ListFormElement(cf.Id.ToString(), cf.Name, cf.Description);
							foreach (ListItemFormElement life in cf.ListOptions)
								lfe.Add(life);

							lfe.Write(sb, fieldValues);
						}
						break;
				}
			}

			return sb.ToString();
		}
	}



}
